package br.com.seosoft.simplecalcfinan;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import br.com.seosoft.simplecalcfinan.utils.IabHelper;
import br.com.seosoft.simplecalcfinan.utils.IabResult;
import br.com.seosoft.simplecalcfinan.utils.Inventory;
import br.com.seosoft.simplecalcfinan.utils.Propaganda;
import br.com.seosoft.simplecalcfinan.utils.Purchase;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class ActComprarItens extends ActivyGeral {

	private IabHelper mHelper;
	public static String base64EncodeKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn94gHZw8kWiS7imLc4w0u5GS0a/KXKly8+2SloeblZGjRcgJM9b6TSx1B6vjjXMD10S0AilnN/ZR12SHGjlZqFPl1Bwm/S3gCZFAyVpPXrqydsWwXxa2+kFxCq+FlfCDbPWGALXFAD4ubsJGP/Ytl9iI+sj6hc4Cl7270zGFe0J9Pirfv4UX2jefhpeIdU5uP7JIXS0SRLmY+JTKtraZXDYISAfhRJk6mUdZVmRhJZo56JVpNwfP1pfTCij/mwjWNuO4ejZP8j4mfNVd7n0rpZ/QPAPWbKhnbT2NsGwjz8mIKgUqC5iwGmyUFPeiop2Qqwu7GqXMjk+zUILvXAz+YQIDAQAB";
	private List<String> additionalSkuList = new ArrayList<String>();
	private TextView descricaoRemoverAds;
	private TextView valorRemoverAds;
	private Button btnComprarRemoverAds;
	private ProgressDialog pbDialogoCarregarItens;
	private IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener;

	// preferences
	private SharedPreferences preference;
	private SharedPreferences.Editor editor;

	// IDS de teste de compra
	public static String ID_TEST_PURCHASED = "android.test.purchased";
	public static String ID_TEST_CANCEL = "android.test.canceled";
	public static String ID_TEST_REEMBOLSO = "android.test.refunded";
	public static String ID_TEST_NAO_TEM_ITEM = "android.test.item_unavailable";

	// IDS de compras reais
	public static String SKU_RETIRAR_ADMOB = "retirar.admob";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_act_comprar_itens);

		descricaoRemoverAds = (TextView) findViewById(R.id.descricaoRemoverAds);
		valorRemoverAds = (TextView) findViewById(R.id.valorRemoveAds);
		btnComprarRemoverAds = (Button) findViewById(R.id.btnComprarRemoverAds);

		// Obtem preferencias salvas
		preference = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());

		editor = preference.edit();

		// Adiciona lista dos itens a comprar
		additionalSkuList.add(SKU_RETIRAR_ADMOB);

		// Inicia barra de progresso
		pbDialogoCarregarItens = new ProgressDialog(ActComprarItens.this);

		pbDialogoCarregarItens.setMessage(getResources().getString(
				R.string.carregando));
		pbDialogoCarregarItens.setCanceledOnTouchOutside(false);
		pbDialogoCarregarItens.onBackPressed();

		// verifica se a barra de progresso foi cancelada para finalizar a
		// atividade e listagem de itens
		pbDialogoCarregarItens.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				// mata a o app billing
				if (mHelper != null)
					mHelper.dispose();
				mHelper = null;

				// mata a atividade
				finish();

			}
		});

		// Exibe barra de progresso inicial
		pbDialogoCarregarItens.show();

		// Inicia service de In-app Billing
		mHelper = new IabHelper(this, base64EncodeKey);
		mHelper.enableDebugLogging(true);

		// Start service das compras
		mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
			public void onIabSetupFinished(IabResult result) {
				if (!result.isSuccess()) {
					// Oh noes, there was a problem.
					Log.d("Iab", "Problem setting up In-app Billing: " + result);

					pbDialogoCarregarItens.dismiss();

				} else {
					mHelper.queryInventoryAsync(true, additionalSkuList,
							mQueryFinishedListener);
				}
				// Hooray, IAB is fully set up!
			}
		});

		// Listener para receber COMPRA FINALIZADA ou ERROS da compras
		mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {

			@Override
			public void onIabPurchaseFinished(IabResult result,
					Purchase purchase) {

				if (result.isFailure()) {
					Log.v("Iab", "Error purchasing: " + result);
					return;
				}

				else if (purchase.getSku().equals(SKU_RETIRAR_ADMOB)) {
					Log.v("Iab", "Finalizado compra : " + result);

					// desativa botao de comprar
					btnComprarRemoverAds.setText(android.R.string.ok);
					btnComprarRemoverAds.setEnabled(false);

					// salva compra nas preferencias
					editor.putBoolean(geral.REMOVEU_ADS, true);
					editor.commit();

				}
				// else if (purchase.getSku().equals()) {
				// // consume the gas and update the UI
				// }
				// else if (purchase.getSku().equals(SKU_PREMIUM)) {
				// // give user access to premium content and update the
				// UI
				// }

			}
		};

	}

	// Listener pare recuperar os itens da google play
	private IabHelper.QueryInventoryFinishedListener mQueryFinishedListener = new IabHelper.QueryInventoryFinishedListener() {

		@Override
		public void onQueryInventoryFinished(IabResult result, Inventory inv) {
			// TODO Auto-generated method stub
			if (result.isFailure()) {
				// handle error
				pbDialogoCarregarItens.dismiss();
				Log.d("Iab", "Erro ao recuperar lista de itens para comprar ");
				Toast.makeText(ActComprarItens.this, "Error a buy item",
						Toast.LENGTH_LONG).show();
				return;
			}

			// recupera o preco e descricao do item e atualiza os campo
			String preco = inv.getSkuDetails(SKU_RETIRAR_ADMOB).getPrice();
			valorRemoverAds.setText(preco);

			String descricao = inv.getSkuDetails(SKU_RETIRAR_ADMOB)
					.getDescription();
			descricaoRemoverAds.setText(descricao);

			// Verifica se ja esta compro os itens

			if (!inv.hasPurchase(SKU_RETIRAR_ADMOB)) {
				btnComprarRemoverAds.setEnabled(true);
			} else {
				btnComprarRemoverAds.setEnabled(false);
				btnComprarRemoverAds.setText(android.R.string.ok);
			}

			Propaganda propaganda = new Propaganda();
			// VERIFICA SE CLIENTE ANTIGO JA PAGOU ANTES PARA DESATIVAS NOVA COMPRA
			if (propaganda.verificarClienteJaPago(ActComprarItens.this)) {
				btnComprarRemoverAds.setEnabled(false);
				btnComprarRemoverAds.setText(android.R.string.ok);
			}

			Log.i("Iab", "Descricao: " + descricao + " Preco: " + preco);

			pbDialogoCarregarItens.dismiss();

		}
	};

	// Realiza a compra do item de remover propagandas
	public void compprarRemoverAds(View v) {

		mHelper.launchPurchaseFlow(ActComprarItens.this, SKU_RETIRAR_ADMOB,
				10001, mPurchaseFinishedListener, "");

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getSupportMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		switch (item.getItemId()) {

		case android.R.id.home:
			finish();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mHelper != null)
			mHelper.dispose();
		mHelper = null;
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

		if (pbDialogoCarregarItens != null
				&& pbDialogoCarregarItens.isShowing()) {
			pbDialogoCarregarItens.dismiss();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d("Iab", "onActivityResult(" + requestCode + "," + resultCode + ","
				+ data);

		// Pass on the activity result to the helper for handling
		if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
			// not handled, so handle it ourselves (here's where you'd
			// perform any handling of activity results not related to in-app
			// billing...
			super.onActivityResult(requestCode, resultCode, data);
		} else {
			Log.d("Iab", "onActivityResult handled by IABUtil.");
		}
	}
}
